import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { DataTemplate } from './data-template.entity';
import { DataRecord } from './data-record.entity';

@Injectable()
export class DataService {
  constructor(
    @InjectRepository(DataTemplate)
    private dataTemplateRepository: Repository<DataTemplate>,
    @InjectRepository(DataRecord)
    private dataRecordRepository: Repository<DataRecord>,
  ) {}

  // 数据模板相关方法
  async findAllTemplates(): Promise<DataTemplate[]> {
    return await this.dataTemplateRepository.find();
  }

  async findOneTemplate(id: number): Promise<DataTemplate | null> {
    return await this.dataTemplateRepository.findOne({ where: { id } });
  }

  async createTemplate(templateData: Partial<DataTemplate>): Promise<DataTemplate> {
    const template = this.dataTemplateRepository.create(templateData);
    return await this.dataTemplateRepository.save(template);
  }

  async updateTemplate(id: number, templateData: Partial<DataTemplate>): Promise<DataTemplate | null> {
    await this.dataTemplateRepository.update(id, templateData);
    return await this.dataTemplateRepository.findOne({ where: { id } });
  }

  async removeTemplate(id: number): Promise<void> {
    await this.dataTemplateRepository.delete(id);
  }

  // 数据记录相关方法
  async findAllRecords(): Promise<DataRecord[]> {
    return await this.dataRecordRepository.find();
  }

  async findRecordsByTemplate(templateId: number): Promise<DataRecord[]> {
    return await this.dataRecordRepository.find({ where: { templateId } });
  }

  async findOneRecord(id: number): Promise<DataRecord | null> {
    return await this.dataRecordRepository.findOne({ where: { id } });
  }

  async createRecord(recordData: Partial<DataRecord>): Promise<DataRecord> {
    const record = this.dataRecordRepository.create(recordData);
    return await this.dataRecordRepository.save(record);
  }

  async updateRecord(id: number, recordData: Partial<DataRecord>): Promise<DataRecord | null> {
    await this.dataRecordRepository.update(id, recordData);
    return await this.dataRecordRepository.findOne({ where: { id } });
  }

  async removeRecord(id: number): Promise<void> {
    await this.dataRecordRepository.delete(id);
  }
}